<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>
<script>

import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from '../../views/dashboard/admin/components/mixins/resize'

export default {
  name: 'DistributeMathBar',
  description: '残差分布图',
  components: {},
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '500px'
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null,
      listData: [],
      xAxis: []
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        if (this.chart !== null) {
          this.initFailureBarVertical(val)
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.initFailureBarVertical(this.chartData)
    },
    sum(array) {
      let s = 0
      array.forEach(function(val, idx, arr) {
        s += Number(val)
      }, 0)
      return s
    },
    // 求和
    sumXY(x, y) {
      return Number(x) + Number(y)
    },
    // 求平方
    square(x) {
      return Number(x) * Number(x)
    },
    initFailureBarVertical({ values, stdev, avg, min, max }) {
      values.forEach(e => {
        this.listData.push(e)
      })

      const objGroup = this.listData.reduce(function(obj, name) {
        obj[name] = obj[name] ? ++obj[name] : 1
        return obj
      }, {})

      // 求数组的最大值和最小值
      // const max = Math.max(...this.listData)
      // const min = Math.min(...this.listData)
      // x轴最大最小前后范围
      const dataRangeMinOP = 2
      const dataRangeMaXOP = 2.1

      // 间距 ，X轴的步距
      const dataRangeOP = 0.1
      // 小数点位数.这个要和数据精确到哪一位相匹配
      const Xpiont = 1
      // 处理x轴，把数据范围内的x轴求出来，并设置值轴没有的值为空，按顺序对应
      this.xAxis = []
      for (let i = min - dataRangeMinOP; i <= max + dataRangeMaXOP; i += dataRangeOP) {
        const str = i.toFixed(Xpiont).toString()
        this.xAxis.push(str)
        if (objGroup[str] == null) {
          objGroup[str] = 0
        }
      }
      const barYaxis = []
      Object.keys(objGroup).sort(function(a, b) {
        return parseFloat(a) - parseFloat(b)
      }).map(key => {
        const num = Math.floor((objGroup[key] / this.listData.length * 100) * 100) / 100
        barYaxis.push(num)
      })

      // 计算正太曲线
      function NDjs(array) {
        const NDarr = []
        for (let i = 0; i < array.length; i++) {
          const ND = (Math.sqrt(2 * Math.PI) * stdev) * Math.pow(Math.E, (-(Math.pow(array[i] - avg, 2) / (2 * Math.pow(stdev, 2)))))
          NDarr.push(ND)
        }
        return NDarr
      }

      const lineYaxis = NDjs(this.xAxis)

      // 配置项，本身项目是可以动态在页面配置修改这些属性的，贴到这里用了默认值
      const opacityOption = 'off'
      let opacity = 0.5
      if (opacityOption === 'off') {
        opacity = 0
      }
      const endPositionOption = 'all'
      const endPositionPercentum = ''
      let endPosition
      if (endPositionOption === 'all') {
        endPosition = 100
      } else if (endPositionOption === 'third') {
        endPosition = 29
      } else {
        endPosition = endPositionPercentum
      }

      const persents = 'on'
      let format1
      let format2
      if (persents === 'on') {
        format1 = '{value} %'
        format2 = '{c} %'
      }
      const data = []
      const lineDataSet = {
        type: 'line',
        symbol: 'none', // 默认是空心圆（中间是白色的），改成实心圆 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow', 'none'
        smooth: true,
        yAxisIndex: 1,
        areaStyle: {
          opacity: opacity
        },
        data: lineYaxis, // 正态分布的值
        name: '标准化残差曲线',
        itemStyle: {
          normal: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: '#FD723CFF' // 0% 处的颜色
                },
                {
                  offset: 0.45,
                  color: '#FD723CFF' // 45% 处的颜色
                },
                {
                  offset: 0.85,
                  color: '#FF5B82FF' // 85% 处的颜色
                },
                {
                  offset: 1,
                  color: '#FF5B82FF' // 100% 处的颜色
                }
              ],
              global: false // 缺省为 false
            },
            label: {
              formatter: format2,
              show: false, // 开启显示
              position: 'top', // 在上方显示
              textStyle: { // 数值样式
                fontSize: 16
              }
            }
          }
        }
      }
      const barDataSet = {
        type: 'bar',
        smooth: true,
        yAxisIndex: 0,
        areaStyle: {
          opacity: opacity
        },
        data: barYaxis, // 柱子的值
        name: '实际分布',
        itemStyle: {
          normal: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: '#79c7f3FF' // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: '#7E7CEB' // 100% 处的颜色
                }
              ],
              global: false // 缺省为 false
            },
            label: {
              formatter: format2,
              show: false, //开启显示
              position: 'top', //在上方显示
              textStyle: { //数值样式
                fontSize: 16
              }
            }
          }
        }
      }
      data.push(lineDataSet, barDataSet)
      const option = {
        type: 'scroll',
        title: {
          text: ''
        },
        // 区域缩放
        dataZoom: [
          {
            type: 'inside',
            show: false,
            xAxisIndex: [0],
            start: 0,
            end: endPosition,
            borderColor: '#F5A9D0',
            backgroundColor: '#F5A9D0'
          },
          {
            show: false,
            type: 'slider',
            xAxisIndex: [0],
            start: 0,
            end: endPosition
          }
        ],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['标准化残差曲线', '实际分布']
        },
        xAxis: {
          name: '',
          nameTextStyle: {
            align: 'left',
            fontSize: 14,
            fontFamily: 'Microsoft YaHei',
            fontWeight: 400,
            color: '#989DAA'
          },
          boundaryGap: false,
          type: 'category',
          data: this.xAxis
        },
        yAxis: [{
          name: '频数',
          nameTextStyle: {
            align: 'right',
            fontSize: 14,
            fontFamily: 'Microsoft YaHei',
            fontWeight: 400,
            color: '#989DAA'
          },
          type: 'value',
          axisLabel: {
            formatter: format1
          }
        }, {
          show: false,
          type: 'value',
          axisLabel: {
            formatter: '{value} %'
          }
        }],
        grid: [{
          show: false,
          top: '15%',
          bottom: '10%',
          left: '10%',
          right: '5%'
        }],
        series: data
      }
      this.chart.setOption(option)
    }
  }

}
</script>
<style lang="scss" scoped>
.bar-vertical-pic {
  padding: 0 0px;
}
</style>
